﻿using System;
using System.IO;
using System.Xml.Serialization;

namespace Dotnet.Utils.Utility.Xml
{
    public static class XmlUtil
    {
        public static string Serialize(object obj)
        {
            XmlSerializer xmlSerializer = new XmlSerializer(obj.GetType());
            string result;
            using (StringWriter stringWriter = new StringWriter())
            {
                xmlSerializer.Serialize(stringWriter, obj);
                using (StringReader stringReader = new StringReader(stringWriter.GetStringBuilder().ToString()))
                {
                    result = stringReader.ReadToEnd();
                }
            }
            return result;
        }

        public static T Deserialize<T>(string str)
        {
            T result;
            try
            {
                Validate(str);
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
                using (StringReader stringReader = new StringReader(str))
                {
                    result = (T)xmlSerializer.Deserialize(stringReader);
                }
            }
            catch (Exception innerException)
            {
                throw new Exception("无法发序列化：" + str, innerException);
            }
            return result;
        }

        public static T DeserializeFromFile<T>(string fileName)
        {
            string str = File.ReadAllText(fileName);
            return Deserialize<T>(str);
        }

        public static void Validate(string str)
        {
            if (str.Contains("<!ENTITY") || str.Contains("ObjectDataProvider") || str.Contains("ExpandedWrapper"))
            {
                throw new Exception("非法的Xml：" + str);
            }
        }
    }
}